var express = require('express');
var router = express.Router();
const bcrypt = require('bcryptjs')
const db = require('../sql/connect')
const NodeRSA = require("node-rsa");
const crypto = require("crypto");
const SECRET = 'asdasfas#$@!%!%!!AWE'


router.post('/', async (req, res, next) => {
    let sql = 'select * from useritem where username = ?';
    db.base(sql, req.body.username, (response) => {
        if (response.results.length == 0) {
            return res.json({
                "type": "error",
                "content": "用户不存在"
            });
        } else {
            if (bcrypt.compareSync(req.body.password, response.results[0].password)) {
                //成功登录
                //生成token
                const jwt = require('jsonwebtoken')
                const token = jwt.sign({ 
                    username: req.body.username,  
                },SECRET)
                console.log(token)
                res.json({
                    "type": "success",
                    "token":token
                });
            } else {
                res.json({
                    "type": "error",
                    "content": "密码错误"
                });
            }

        }
    });
});

module.exports = router;